import { Injectable } from '@nestjs/common';
import { FilestDao as Dao } from '@/servers/daos/common/files/files.dao';
import { from } from 'rxjs';
import { join, parse } from 'path';
import { response } from 'express';

@Injectable()
export class FilesService {

    private rootPath = join(__dirname, '../../../../');

    constructor(
        private dao: Dao
    ) { }

    /**
     * 添加文件
     */
    add(params: any): Promise<any> {
        return this.dao.add(params);
    }

    /**
     * 通过type查询所有:组合查询条件
     */
    async upload(file: any, body: any): Promise<any> {
        console.log(file, body)
        const self = this;
        const fs = require("fs");
        //根目录
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let timestamp = Date.parse(date.toString());
        let file_path = null;
        let child_path = 'public\\upload\\' + year + month + day;
        try {
            await fs.promises.stat(this.rootPath + child_path);
        } catch (e) {
            // 不存在文件夹，直接创建 {recursive: true} 这个配置项是配置自动创建多个文件夹
            await fs.promises.mkdir(this.rootPath + child_path, { recursive: true })
        }
        file_path = this.rootPath + child_path;
        let _filename = timestamp + file.originalname.substr(file.originalname.indexOf('.'));
        let _path = join(file_path, _filename);
        return new Promise((resolve, reject) => {
            fs.writeFile(_path, file.buffer, function (err) {
                if (err) {
                    reject(err);
                }
                let params = {
                    origin_name: file.originalname,
                    file_name: _filename,
                    file_url: child_path,
                    file_type: body.file_type,
                    file_format: file.mimetype,
                    user_id: body.userId,
                    server_id: body.serverId
                }
                let data = self.dao.add(params);
                resolve(data);
            });
        });
    }

    /**
     * 展示图片
     * @param id 
     */
    showImg(params: any, response: any): void {
        var fs = require('fs');
        let id = parseInt(params.id);
        if (typeof id == 'number' && id > 0) {
            this.dao.findOne(id).then(res => {
                let file_name = 'null.jpg';
                if (res && res.file_name) {
                    file_name = res.file_url + '\\' + res.file_name;
                }
                let _path = this.rootPath + file_name;
                fs.readFile(_path, 'binary', function (err, file) {
                    if (err) {
                        console.log('图片错误', err);
                    } else {
                        response.write(file, 'binary');
                    }
                    response.end();
                });
            });
        } else {
            console.log('错误图片ID');
        }
    }
}
